var userType;
Ext.Ajax.request({
	url : "getSession",
	params : {
	},
	type : "POST",
	timeout : 4000,
	async:false,
	success : function(response, opts) {
		var user = eval('('+response.responseText+')');
		userType = user[0].userType;
	}
});		 

function showErrorMsg(msg){
	Ext.example.msg('', msg, '');
}
		                    	
var tbar = Ext.create('Ext.toolbar.Toolbar', {
	dock : 'top',
	layout: {  
        overflowHandler: 'Menu'  
    },  
	items : [{
		id:'cpName',
		xtype : 'textfield',
		name : 'cpName',
		fieldLabel : '客户名称',
		labelWidth : 60,
		width : 220,
		emptyText : '===请填写客户名称===',
		listeners:{
			'blur':function(){
				search();
			}
		}
	},{
		id:'cpCode',
		xtype : 'textfield',
		name : 'cpCode',
		fieldLabel : '客户编码',
		labelWidth : 60,
		width : 220,
		emptyText : '===请填写客户编码===',
		listeners:{
			'blur':function(){
				search();
			}
		}
	},{
		text : '查询',
		handler : function() {
			search();
		}
	},{
		text : '重置',
		handler : function() {
			Ext.getCmp("cpName").setValue("");
			Ext.getCmp("cpCode").setValue("");
			search();
		}
	}]
});

function search(){
	var cpName = Ext.getCmp("cpName").getValue();
	var cpCode = Ext.getCmp("cpCode").getValue();
	
	// 获取grid的store
	var cpStore = Ext.getCmp("cpGrid").getStore();
	cpStore.load({
		params : {
			cpName : encodeURIComponent(cpName),
			cpCode : cpCode
        }
	});
}

Ext.define("app.view.CPGrid", {
			extend : "Ext.grid.Panel",
			xtype: 'cell-editing',
			alias : "widget.cpGrid",
			id : "cpGrid",
			width:700,
			height:350,
			viewConfig:{
		         loadMask:false  // grid去掉加载中的提示
		    },
			selModel : {
				//selType : "checkboxmodel"
			},
			border : 0,
			multiSelect : true,
			frame : false, // 不要边框
			tbar : tbar,
			bbar : {
				xtype : 'pagingtoolbar',
				store : 'CPStore',
				dock : 'bottom',
				displayInfo : true
			},
			viewConfig:{  
		        enableTextSelection:true  // 文本可选择
		    },
			enableKeyNav : true,
			columnLines : true,
			forceFit :true, // 宽度自适配
			columns : [{
						text:"序号",
						dataIndex:"id",
						width:20
					},{
						text : "CP名称",
						dataIndex : "cpName",
						width : 60,
		                editor: {
		                	xtype : "textfield"
		                }
					},{
						text : "CP编号",
						dataIndex : "cpCode",
						width : 70,
		                editor: {
		                	xtype : "textfield"
		                }
					},{
						text : "所属团队",
						dataIndex : "teamName",
						width : 70,
		                editor: {
		                	xtype : "textfield"
		                }
					},{
						text : "所属商务",
						dataIndex : "bussinessName",
						width : 70,
		                editor: {
		                	xtype : "textfield"
		                }
					},{
						text : "是否可用",
						dataIndex : "statue",
						width : 40,
						editor : {
			                xtype : 'combobox',
			                editable : false,
			             //   disabled:true,
			                store : [['0', '正常'],
	                         ['1', '不可用']
			            ]},
						renderer : function(v, p, record, rowIndex, colIndex) { // 值自定义渲染
					        if (v==1) {
					        	v = "<font style='color:red'>不可用</font>";
					        }else{
					        	v = "正常";
					        }
					        return v;
					    }
					},{
						text : "状态",
						dataIndex : "verifyStatue",
						width : 60,
						editor : {
			                xtype : 'combobox',
			                editable : false,
			             //   disabled:true,
			                store : [['1', '待审核'],
	                         ['2', '审核成功'],
	                         ['3', '审核失败']
			            ]},
						renderer : function(v, p, record, rowIndex, colIndex) { // 值自定义渲染
							var errorMsg = record.get('verifyMsg');
					        if (v==1) {
					        	v = "待审核";
					        }else if (v==2) {
					        	v = "审核成功";
					        }else if (v==3) {
					        	v = "<font style='color:red'>审核失败,<a href='javascript:;' onclick=showErrorMsg('"+errorMsg+"')>原因</a></font>";
					        }
					        return v;
					    }
					},{
		                xtype: 'actioncolumn',
		                width: 20,
		                tdCls: 'action',  
		                text: '操作',  
		                sortable: false,
		                menuDisabled: true,
		                items: [{
		                	icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/edit.png',
		                    tooltip: '处理',
		                    scope: this,
		                    handler: function(grid, rowIndex, colIndex) {
		                    	var record = grid.getStore().getAt(rowIndex);
		                        var id = record.get('id');
		                        var statue = record.get('statue');
		                        var verifyStatue = record.get('verifyStatue');
		                        this.updateCPById(grid,id,statue,verifyStatue);
		                    },
		                    getClass: function(v, meta, record) {
		                    	var verifyStatue = record.get('verifyStatue');
		                    	if(userType == '6'){
		                    		// 商务经理只能查看 不能编辑
		                    		return 'emptyCss';
		                    	}else if (userType == '7' && verifyStatue != '3') {
		                        	return 'emptyCss';
		                        }else if((userType == '1' || userType == '2' || userType == '3') && (verifyStatue == '2' || verifyStatue == '3')){
		                        	return 'emptyCss';
		                        }else{
		                        	return '';
		                        }
		                    }
		                },{
		                	icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/change.png',
		                    tooltip: '状态切换',
		                    scope: this,
		                    handler: function(grid, rowIndex, colIndex) {
		                        var record = grid.getStore().getAt(rowIndex);
		                        var id = record.get('id');
		                        var statue = record.get('statue');
		                        this.deleteCpInfo(grid,id,statue);
		                    },
		                    getClass: function(v, meta, record) {
		                    	var statue = record.get('statue');
		                    	var verifyStatue = record.get('verifyStatue');
		                    	if(statue == '1' && verifyStatue == '2'){
		                    		if(userType == '1' || userType == '2' || userType == '3'){
		                    			return '';
		                    		}else{
		                    			return 'emptyCss';
		                    		}
		                    	}else if(statue == '0'){
		                    		// 只有管理员 运营 可以切换状态
		                    		if(userType == '1' || userType == '2' || userType == '3'){
		                    			return '';
		                    		}else{
		                    			return 'emptyCss';
		                    		}
		                        }else{
		                        	return 'emptyCss';
		                        }
		                    }
		                }
		                ]
		            }],
			listeners: { 
				beforeedit: function (editor, e, eOpts) {
					if(e.record.raw.sing){
						return true;
					}else{
						return false;
					}
		        }
			},					
			initComponent : function() {
				// 可编辑插件
				this.editing = Ext.create("Ext.grid.plugin.CellEditing");
				this.plugins = [this.editing];
				this.callParent(arguments);
			},
			store : "CPStore"
});

// 根据id删除CP
function deleteCpInfo(grid,id,statue){
	if(statue != 0){
		statue = 0;
	} else {
		statue = 1;
	}	
		
	var store = grid.getStore();
	Ext.Ajax.request({
		url : "deleteCpById",
		params : {
			id : id,
			statue : statue
		},
		type : "POST",
		timeout : 4000,
		success : function(response, opts) {
			var result = eval('('+response.responseText+')');
			if(result.resultCode == 'success'){
				// 刷新grid
				store.load();
				Ext.example.msg('', '切换成功', '');
			}else if(result.resultCode == 'exsist'){
				Ext.example.msg('', '切换失败<br/>'+result.errorInfo, '');
			}else{
				Ext.example.msg('', '切换失败', '');
			}
		}
	});
}

var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"正在加载中..."});  

function updateCPById(grid,id,statue,verifyStatue){
	if(userType == '7'){
		if(verifyStatue != '3'){
			Ext.example.msg('', '该状态不允许编辑', '');
		}else{
			var store = grid.getStore();
			 var win = Ext.create('Ext.window.Window', {
			    	autoShow: false,
			        title: '修改客户信息',
			        width: 460,
			        height: 560,
			        minWidth: 300,
			        minHeight: 200,
			        layout: 'fit',
			        plain:true,
			        modal: 'true',  // 模态
			        collapsible: true, //允许缩放条  
			        closeAction: 'destroy',  
			        autoScroll: true,
			        maximizable :true,
			        loader: {
			            url:'updateBaseCPInfo?id='+id,
			            scripts: true,
			            autoLoad: true
			        },
			        listeners:{
			        	'beforerender':function(){
			        		myMask.show();  
			        	}
			       },
			        buttonAlign: "center",  
			        buttons: [{
			            text: '保存',
			            handler: function() {
			            	//将form表单提交过来数据转换为json
			            	var cpJson = {}; 
			            	var a = $("#update_cp_form").serializeArray();    
			        	    $.each(a, function() {    
			        	       if (cpJson[this.name]) {    
			        	           if (!cpJson[this.name].push) {    
			        	        	   cpJson[this.name] = [cpJson[this.name]];    
			        	           }    
			        	           cpJson[this.name].push(this.value || '');    
			        	       } else {    
			        	    	   cpJson[this.name] = this.value || '';    
			        	       }    
			        	   }); 
			            	
			               if(validate(cpJson)){
			            		Ext.Ajax.request({
									url : "updateCPInfo",
									jsonData : Ext.encode(cpJson),
									method : "post",
									timeout : 4000,
									success : function(response, opts) {
										var result = eval('('+response.responseText+')');
										if(result.resultCode == 'success'){
											// 刷新grid
											store.load();
											//将修改表示初始化
											Ext.example.msg('', '更新成功', '');
											// 关闭窗口
				        					win.close();
										}else if(result.resultCode == 'fail'){
											Ext.example.msg('', 'CP名称或者CP编码不能重复', '');
										} else {
											Ext.example.msg('', '更新失败', '');
										}
									}
								});
			            	}
			            }
			        },{
			            text: '取消',
			            handler: function() {
			            	// 关闭窗口
			            	win.close();
			            }
			        }]
			    });
			    win.show();
		}
	}else if(userType == '1' || userType == '2' || userType == '3'){
		if(verifyStatue == '2' || verifyStatue == '3'){
			Ext.example.msg('', '该状态不允许审核', '');
		}else{
			var store = grid.getStore();
			 var win = Ext.create('Ext.window.Window', {
			    	autoShow: false,
			        title: '审核客户信息',
			        width: 460,
			        height: 560,
			        minWidth: 300,
			        minHeight: 200,
			        layout: 'fit',
			        plain:true,
			        modal: 'true',  // 模态
			        collapsible: true, //允许缩放条  
			        closeAction: 'destroy',  
			        autoScroll: false,
			        maximizable :true,
			        loader: {
			            url:'verifyCPInfo?id='+id,
			            scripts: true,
			            autoLoad: true
			        },
			        listeners:{
			        	'beforerender':function(){
			        		myMask.show();  
			        	}
			       },
			        buttonAlign: "center",  
			        buttons: [{
			            text: '审核失败',
			            handler: function() {
			            	//将form表单提交过来数据转换为json
			            	var cpJson = {}; 
			            	var a = $("#verify_cp_form").serializeArray();    
			        	    $.each(a, function() {    
			        	       if (cpJson[this.name]) {    
			        	           if (!cpJson[this.name].push) {    
			        	        	   cpJson[this.name] = [cpJson[this.name]];    
			        	           }    
			        	           cpJson[this.name].push(this.value || '');    
			        	       } else {    
			        	    	   cpJson[this.name] = this.value || '';    
			        	       }    
			        	   });
			        	   cpJson["verifyStatue"] = 3;
			            	
			               if(validateVerify(cpJson)){
			            		Ext.Ajax.request({
									url : "verifyCP",
									jsonData : Ext.encode(cpJson),
									method : "post",
									timeout : 4000,
									success : function(response, opts) {
										var result = eval('('+response.responseText+')');
										if(result.resultCode == 'success'){
											// 刷新grid
											store.load();
											//将修改表示初始化
											Ext.example.msg('', '处理成功', '');
											// 关闭窗口
				        					win.close();
										}else {
											Ext.example.msg('', '处理失败', '');
										}
									}
								});
			            	}
			            }
			        },{
			            text: '审核成功',
			            handler: function() {
			            	//将form表单提交过来数据转换为json
			            	var cpJson = {}; 
			            	var a = $("#verify_cp_form").serializeArray();    
			        	    $.each(a, function() {    
			        	       if (cpJson[this.name]) {    
			        	           if (!cpJson[this.name].push) {    
			        	        	   cpJson[this.name] = [cpJson[this.name]];    
			        	           }    
			        	           cpJson[this.name].push(this.value || '');    
			        	       } else {    
			        	    	   cpJson[this.name] = this.value || '';    
			        	       }    
			        	   }); 
			        	    cpJson["verifyStatue"] = 2;
			            	
			        	    Ext.Ajax.request({
								url : "verifyCP	",
								jsonData : Ext.encode(cpJson),
								method : "post",
								timeout : 4000,
								success : function(response, opts) {
									var result = eval('('+response.responseText+')');
									if(result.resultCode == 'success'){
										// 刷新grid
										store.load();
										//将修改表示初始化
										Ext.example.msg('', '处理成功', '');
										// 关闭窗口
			        					win.close();
									}else {
										Ext.example.msg('', '处理失败', '');
									}
								}
							});
			            }
			        },{
			            text: '取消',
			            handler: function() {
			            	// 关闭窗口
			            	win.close();
			            }
			        }]
			    });
			    win.show();
		}
		
	}
	
}
